<template>
  <view class="health-detail">
    <view class="health-detail">
      <view
        v-if="showCodeUrl && tabList.length > 1"
        class="health-detail-top px-24rpx"
      >
        <view class="code-tab">
          <view
            v-for="item in tabList"
            class="code-tab-item"
            :class="tabActive === item.value ? 'active' : ''"
            @click="tabChange(item)"
          >
            {{ item.title }}
          </view>
        </view>
      </view>
      <view class="px-24rpx py-30rpx">
        <view
          class="bg-white rounded-16rpx p-26rpx"
          :class="showCodeUrl && tabList.length > 1 ? 'mt-112rpx' : ''"
        >
          <!-- 二维码区域 -->
          <view
            v-if="showCodeUrl"
            class="qr-container pt-110rpx flex justify-center mb-82rpx"
          >
            <PatientCode
              size="330rpx"
              :patientInfo="patientInfo"
              :type="tabActive === 1 ? 'registration' : 'health'"
              :show-popup="false"
            ></PatientCode>
          </view>

          <!-- 信息卡片 -->
          <view class="info-card bg-[#F5F7F7] p-32rpx rounded-16rpx">
            <view class="info-item">
              <text class="label">姓名</text>
              <text class="value">
                {{ patientInfo.name }}
                {{ sexEnum(patientInfo.sex) }}
                {{ patientInfo.age }}岁
              </text>
            </view>
            <view class="info-item">
              <text class="label">手机号</text>
              <text class="value">{{
                healthCardUtil.maskPhone(patientInfo.phone)
              }}</text>
            </view>
            <view class="info-item">
              <text class="label">身份证号码</text>
              <text class="value">{{
                healthCardUtil.maskIdCard(patientInfo.certId)
              }}</text>
            </view>
            <view class="info-item">
              <text class="label">卡号</text>
              <text class="value break-all">{{ card || '--' }}</text>
            </view>
          </view>
        </view>

        <!-- 操作按钮 -->
        <view
          v-if="Object.keys(patientInfo).length"
          class="action-buttons py-32rpx mt-24rpx flex bg-white rounded-16rpx"
        >
          <view
            class="action-button flex flex-col items-center"
            @click="handleUnbind"
          >
            <image
              class="w-82rpx h-82rpx"
              :src="specUrl('20250529/unbind_icon.png')"
            ></image>
            <text class="text-28rpx text-[#333333] mt-16rpx">解绑</text>
          </view>
          <view
            v-if="!patientInfo.healthCardId"
            class="action-button flex flex-col items-center"
            @click="handleUpdate"
          >
            <image
              class="w-82rpx h-82rpx"
              :src="specUrl('20250529/update_icon.png')"
            ></image>
            <text class="text-28rpx text-[#333333] mt-16rpx">升级为健康卡</text>
          </view>
          <view
            v-if="patientInfo.healthCardId"
            class="action-button flex flex-col items-center"
            @click="handleEdit"
          >
            <image
              class="w-82rpx h-82rpx"
              :src="specUrl('20250529/editor_icon.png')"
            ></image>
            <text class="text-28rpx text-[#333333] mt-16rpx">修改</text>
          </view>
          <view
            v-if="!patientInfo.isDefault"
            class="action-button flex flex-col items-center"
            @click="handleDefault"
          >
            <image
              class="w-82rpx h-82rpx"
              :src="specUrl('20250529/default_icon.png')"
            ></image>
            <text class="text-28rpx text-[#333333] mt-16rpx">设为默认</text>
          </view>
        </view>
      </view>
    </view>
    <Dialog
      ref="unBindDialog"
      :show="showUnBind"
      type="comfrim"
      title="温馨提示"
      @close="closeUnBind"
      @submit="confirmUnBind"
    >
      <view class="text-30rpx text-[#333] mt-30rpx mb-60rpx text-center">
        即将解绑就诊卡，是否继续解绑？
      </view>
    </Dialog>
  </view>
</template>

<script setup>
  import { onLoad, onShow } from '@dcloudio/uni-app';
  import { ref, computed, onMounted } from 'vue';
  import { specUrl } from '@/utils/icon';
  import { sexEnum } from '@/utils/util';
  import {
    patientDetail,
    setDefaultPatient,
    delPatient,
  } from '@/resource/patient';
  import healthCard from '../../healthCard/static/ElectronicHealthCard';
  import healthCardUtil from '@/utils/healthCard/index';
  import { usePatientStore } from '@/store/patient';
  import themeStore from '@/store/theme';

  const themeColor = themeStore().themeColor;

  const patientStore = usePatientStore();

  const id = ref();
  const patientInfo = ref({});
  const tabActive = ref(1);
  const tabList = computed(() => {
    const list = [
      {
        title: '就诊卡',
        value: 1,
        show: patientInfo.value?.registrationCode,
      },
      {
        title: '电子健康卡',
        value: 2,
        show: patientInfo.value?.healthCardId,
      },
    ];
    return list.filter(item => item.show);
  });
  const tabChange = item => {
    tabActive.value = item.value;
  };
  // 是否存在患者信息
  const hasPatientInfo = computed(() => {
    return patientInfo.value && Object.keys(patientInfo.value).length > 0;
  });
  // 卡号
  const card = computed(() => {
    if (!hasPatientInfo.value) return '';
    // 电子健康卡优先
    return tabActive.value === 1
      ? patientInfo.value.registrationCode
      : patientInfo.value.healthCardId;
  });
  // 默认展示
  const showCodeUrl = computed(() => {
    if (!hasPatientInfo.value) return '';
    // 电子健康卡优先
    return patientInfo.value?.qrCodeText || patientInfo.value?.barCode;
  });

  onLoad(options => {
    id.value = options.id;
  });

  const loadTabActive = () => {
    if (tabList.value.some(it => it.value == 1)) {
      tabActive.value = 1;
    } else {
      tabActive.value = 2;
    }
  };

  // 获取就诊人详情
  onShow(() => {
    connectHealthCard();
  });

  // 获取就诊人详情
  const getPatientInfo = async () => {
    return new Promise((resolve, reject) => {
      patientDetail(id.value)
        .then(({ data }) => {
          console.log('patientInfo', data);
          patientInfo.value = data;
          loadTabActive();
          resolve();
        })
        .catch(reject);
    });
  };

  // 解绑
  const showUnBind = ref(false);
  const unBindDialog = ref();
  const handleUnbind = () => {
    showUnBind.value = true;
  };
  const confirmUnBind = async () => {
    try {
      healthCardUtil.showLoad('解绑中');
      await delPatient(id.value);
      healthCardUtil.hideLoad();
      patientStore.updatePatient(patientInfo.value, 'del');
      healthCardUtil.toast('解绑成功', uni.navigateBack);
    } catch (err) {
      console.log(err);
      healthCardUtil.hideLoad(1500);
    }
  };
  const closeUnBind = () => {
    unBindDialog.value.close();
  };
  // 编辑
  const handleEdit = async () => {
    healthCardUtil.verify({
      scene: healthCardUtil.getScene('change_patient'),
      patientInfo: patientInfo.value,
      success: () => {
        // uni.navigateTo({
        //   url: `/patientPages/healthCard/useFrom/index?patientId=${patientInfo.value.id}`,
        // });
        uni.navigateTo({
          url: `/patientPages/patient/detail/index?id=${patientInfo.value.id}`,
        });
      },
    });
  };
  // 设为默认
  const handleDefault = async () => {
    try {
      healthCardUtil.showLoad('设置中');
      await setDefaultPatient(id.value);
      await getPatientInfo();
      patientStore.updatePatient();
      healthCardUtil.hideLoad();
      healthCardUtil.toast('设置成功');
    } catch (err) {
      console.log(err, '设为默认');
      healthCardUtil.hideLoad(1500);
    }
  };
  // 升级为健康卡
  const handleUpdate = async () => {
    healthCardUtil.update(patientInfo.value.id);
  };

  // 健康卡关联院内
  async function connectHealthCard() {
    try {
      const isResult = healthCard.hasResult();
      if (!isResult) {
        healthCardUtil.showLoad();
        await getPatientInfo();
        healthCardUtil.hideLoad();
        return;
      }
      healthCardUtil.showLoad('升级中');
      // 获取健康卡信息
      const res = await healthCard.getInfo();
      console.log('【健康卡信息】', res);
      if (!res.data || !res.data.healthCardId) {
        healthCardUtil.toast('未获取到健康卡数据，请重试');
        return;
      }
      await healthCard.updateByHealthCard(res.data, id.value);
      await getPatientInfo();
      patientStore.updatePatient(patientInfo.value);
      healthCardUtil.hideLoad();
      healthCardUtil.toast('升级成功');
    } catch (err) {
      console.log('【更新建档 结果】', err);
      healthCardUtil.hideLoad(1500);
    }
  }
</script>

<style lang="scss">
  .health-detail {
    &-top {
      position: fixed;
      top: 0;
      z-index: 10;
      width: 100%;
      background-color: #fff;
      height: 128rpx;
      display: flex;
      align-items: center;
      .code-tab {
        width: 100%;
        height: 94rpx;
        margin: 0 auto;
        padding: 8rpx;
        display: flex;
        justify-content: space-between;
        background: #f5f5f5;
        border-radius: 48rpx;
        position: relative;
        &-item {
          color: #333;
          font-size: 32rpx;
          width: 244rpx;
          display: flex;
          justify-content: center;
          align-items: center;
          border-radius: 38rpx;
          flex: 1;
          margin-right: 22rpx;
          &:last-child {
            margin-right: 0;
          }
          &.active {
            background: var(--primary-btn-color);
            color: #ffffff;
            font-weight: 500;
          }
        }
      }
    }
    .info-item {
      display: flex;
      justify-content: space-around;
      margin-bottom: 16rpx;
      font-size: 28rpx;
      color: #333333;
      line-height: 40rpx;

      &:last-child {
        margin-bottom: 0;
      }
      .label {
        width: 214rpx;
      }
      .value {
        flex: 1;
        text-align: right;
      }
    }
    .action-buttons {
      .action-button {
        width: 33.33%;
      }
    }
  }
</style>
